//
//  HJShareToSessionController.m
//  KaiChat
//
//  Created by lx on 2024/3/6.
//

#import "HJShareToSessionController.h"
#import "HJIM.h"
#import "HJOrderedDictionary.h"
#import "HJShareToSessionCell.h"
#import "HJSearchView.h"
#import "TJEmptyDataHandler.h"
#import "HJSelectShareView.h"


@interface HJShareToSessionController ()<QMUITextFieldDelegate>

@property (nonatomic, strong) NSArray *datas;
@property (nonatomic, strong) HJOrderedDictionary *sessionDict;
@property (nonatomic, strong) NSMutableArray *searchDatas;
@property (nonatomic, strong) NSArray *originalDatas;
@property (nonatomic, strong) TJEmptyDataHandler *emptyDataHandler;
@property (nonatomic, strong) HJChatGroupModel *groupModel;
@property (nonatomic, weak) HJSelectShareView *selectMemberView;
@property (nonatomic, weak) UIView *searchView;
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, weak) QMUITextField *textField;
@property (nonatomic, assign) NSInteger count;


@end

@implementation HJShareToSessionController

- (void)viewDidLoad {
    [super viewDidLoad];
    

    self.view.backgroundColor = UIColor.whiteColor;
    
    UIView *headerView = [UIView addToView:self.view];
    headerView.backgroundColor = UIColor.whiteColor;
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.offset(0);
        make.height.offset(60);
    }];
    
    HJSearchView *searchView = [HJSearchView addToView:headerView];
    searchView.backgroundColor = UIColor.tj_F6F6F6Color;
    searchView.addCornerRadius(10);
    [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(leftRightMargin);
        make.top.offset(10);
        make.height.offset(40);
    }];
    
    QMUITextField *textField = searchView.textField;
    textField.placeholder = @"Search";
    textField.maximumTextLength = 30;
    textField.returnKeyType = UIReturnKeyDone;
    textField.delegate = self;
    [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    _textField = textField;
    
    TJWeakify(self)
    HJSelectShareView *selectMemberView = [HJSelectShareView addToView:headerView];
    [selectMemberView setDidClickDeleteButtonBlock:^(HJShareModel * _Nonnull model) {
        [weakself didSelectRowWithModel:model];
    }];
    [selectMemberView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.height.offset(0);
        make.top.equalTo(searchView.mas_bottom).offset(10);
    }];
    
    _headerView = headerView;
    _selectMemberView = selectMemberView;
    _searchView = searchView;
    
    self.navigationBar.title = @"Select Fridends";
    self.tableViewStyle = UITableViewStylePlain;
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.1)];
    [self.tableView registerClass:HJShareToSessionCell.class forCellReuseIdentifier:@"HJShareToSessionCell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.rowHeight = 64;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView setSectionIndexColor:UIColor.tj_9B9B9BColor];
 
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headerView.mas_bottom);
        make.left.right.bottom.offset(0);
    }];
    
    _emptyDataHandler = [TJEmptyDataHandler emptyDataHandleWithScrollView:self.tableView];
    [self loadData];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if (self.textFieldBeginDidEditBlock) {
        self.textFieldBeginDidEditBlock();
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (self.textFieldEndDidEditBlock) {
        self.textFieldEndDidEditBlock();
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (void)textFieldDidChange:(QMUITextField *)textField {
    
    NSString *keyword = textField.text;
    
    if (isEmptyString(keyword)) {
        for (HJShareModel *obj in self.originalDatas) {
            obj.nameAttributedstring = nil;
        }
        self.emptyDataHandler.canDisplay = YES;
        [self.searchDatas removeAllObjects];
        [self handleModels:self.originalDatas];
        return;
    }
    
    self.emptyDataHandler.canDisplay = NO;
    [self.searchDatas removeAllObjects];
    for (HJShareModel *obj in self.originalDatas) {
        NSRange range = [obj.name rangeOfString:keyword options:NSCaseInsensitiveSearch];
        if (range.location != NSNotFound) {
            
            NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:obj.name];
            [attrStr addAttribute:NSForegroundColorAttributeName value:UIColor.tj_mainColor range:range];
            obj.nameAttributedstring = attrStr;
            [self.searchDatas addObject:obj];
        } else {
            obj.nameAttributedstring = nil;
        }
    }
    
    [self handleModels:self.searchDatas];
}

- (nullable HJShareToSessionCell *)getVisibleCellWithModel:(HJShareModel *)model {
    for (HJShareToSessionCell *cell in self.tableView.visibleCells) {
        if ([[cell.model.anyObject sessionId] isEqualToString:[model.anyObject sessionId]]) {
            return cell;
        }
    }
    return nil;
}

- (void)loadData {
    
    [[HJIM shareIM].conversationManager allConversationListCompletion:^(NSArray * _Nonnull list) {
        
        self.originalDatas = [self transformToShareModels:list];

        dispatch_async_main_queue(^{
            self.emptyDataHandler.canDisplay = YES;
            [self hiddenLoading];
            [self handleModels:self.originalDatas];
        });
        
    }];
}

- (NSArray *)transformToShareModels:(NSArray *)sessionModels {
    NSMutableArray *Marr = [NSMutableArray array];
    for (HJChatSessionModel *sessionModel in sessionModels) {
        if (sessionModel.chatType == HJChatTypeSingle || sessionModel.chatType == HJChatTypeGroup) {
            [Marr addObject:[HJShareModel modeWithSessionModel:sessionModel]];
        }
    }
    return Marr.copy;
}

- (void)updateSelectState:(HJShareModel *)obj {//只设置之前选中的, 默认选中的不处理
    HJShareModel *shareModel = [self.sessionDict objectForKey:[obj.anyObject sessionId]];
    shareModel.isSelect = shareModel.isSelect;
    
    if (obj.isSelect) {
        [self.sessionDict setObject:obj forKey:[obj.anyObject sessionId]];
    }
}

- (void)handleModels:(NSArray *)models {
    self.datas = models;
    [self.tableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJShareToSessionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HJShareToSessionCell" forIndexPath:indexPath];
    HJShareModel *model = self.datas[indexPath.row];
    cell.model = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HJShareModel *model = self.datas[indexPath.row];
    
    [self didSelectRowWithModel:model];
}

- (void)didSelectRowWithModel:(HJShareModel *)model {
    
    model.isSelect = !model.isSelect;
    
    HJShareToSessionCell *cell = [self getVisibleCellWithModel:model];
    cell.model = model;
    if (model.isSelect) {
        [self.sessionDict setObject:model forKey:[model.anyObject sessionId]];
    } else {
        [self.sessionDict removeObjectForKey:[model.anyObject sessionId]];
    }
    
    [self updateSelectMemberViewHeight];
    
    if (self.selectDidChangeBlock) {
        self.selectDidChangeBlock(self.sessionDict.allValues);
    }
}


- (void)updateSelectMemberViewHeight {
    execute(^{
        if (self.sessionDict.count > 0) {
            [self.headerView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.offset(140);
            }];
            [self.selectMemberView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.right.offset(0);
                make.height.offset(80);
                make.top.equalTo(self.searchView.mas_bottom).offset(10);
            }];
        } else {
            [self.headerView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.offset(60);
            }];
            [self.selectMemberView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.right.offset(0);
                make.height.offset(0);
                make.top.equalTo(self.searchView.mas_bottom).offset(10);
            }];
            
        }
    }, ^{
        self.selectMemberView.datas = self.sessionDict.allValues;
    });
}
 
- (BOOL)hiddenNavigationBar {
    return YES;
}
 
- (HJOrderedDictionary *)sessionDict {
    if (!_sessionDict) {
        _sessionDict = [HJOrderedDictionary dictionary];
    }
    return _sessionDict;
}

- (NSMutableArray *)searchDatas {
    if (!_searchDatas) {
        _searchDatas = [NSMutableArray array];
    }
    return _searchDatas;
}

@end

